package com.ds.yuntukubackend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ds.yuntukubackend.config.CosClientConfig;
import com.ds.yuntukubackend.exception.BusinessException;
import com.ds.yuntukubackend.exception.ErrorCode;
import com.ds.yuntukubackend.exception.ThrowUtils;
import com.ds.yuntukubackend.manager.CosManager;
import com.ds.yuntukubackend.manager.FileManager;
import com.ds.yuntukubackend.manager.upload.FilePictureUpload;
import com.ds.yuntukubackend.manager.upload.PictureUploadTemplate;
import com.ds.yuntukubackend.manager.upload.UrlPictureUpload;
import com.ds.yuntukubackend.mapper.PictureMapper;
import com.ds.yuntukubackend.model.dto.file.UploadPictureResult;
import com.ds.yuntukubackend.model.dto.picture.*;
import com.ds.yuntukubackend.model.entity.Picture;
import com.ds.yuntukubackend.model.entity.Space;
import com.ds.yuntukubackend.model.entity.User;
import com.ds.yuntukubackend.model.enums.PictureReviewStatusEnum;
import com.ds.yuntukubackend.model.vo.PictureVO;
import com.ds.yuntukubackend.model.vo.UserVO;
import com.ds.yuntukubackend.service.PictureService;
import com.ds.yuntukubackend.service.SpaceService;
import com.ds.yuntukubackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author lenovo
* @description 针对表【picture(图片)】的数据库操作Service实现
* @createDate 2025-02-02 17:12:08
*/
@Service
@Slf4j
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
    implements PictureService {

    @Resource
    private FileManager fileManager;

    @Resource
    private UserService userService;

    @Resource
    private SpaceService spaceService;

    @Resource
    private FilePictureUpload filePictureUpload;

    @Resource
    private UrlPictureUpload urlPictureUpload;

    @Resource
    private CosManager cosManager;

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private TransactionTemplate transactionTemplate;


    /**
     * 上传图片
     * @param inputSource  文件输入源
     * @param pictureUploadRequest 图片id,没有就是新增图片，有就是重新上传，需把之前的删掉
     * @param loginUser 当前用户，判断权限
     * @return
     */
    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) {
        //todo:删掉用户上传的源图片
        //1.校验参数
        ThrowUtils.throwIf(inputSource == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        //上传到私有空间，需要判断权限：仅能上传到本人空间
        Long spaceId = pictureUploadRequest.getSpaceId();
        if(spaceId != null){
            //通过空间id找到用户id,判断userId 和 loginUser 是否一致
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR,"空间不存在");
            if(!space.getUserId().equals(loginUser.getId())){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
            //校验空间额度：只对当前空间进行校验，不对本次上传后校验
            ThrowUtils.throwIf(space.getTotalSize() >= space.getMaxSize(),ErrorCode.OPERATION_ERROR,"空间大小不足");
            ThrowUtils.throwIf(space.getTotalCount() >= space.getMaxCount(),ErrorCode.OPERATION_ERROR,"空间条数不足");
        }
        //判断是新增还是更新
        Long pictureId = null;
        if(pictureUploadRequest.getId()!=null){
            pictureId = pictureUploadRequest.getId();
        }
        //如果是更新图片，需要校验图片是否存在
        Picture oldPicture;
        if(pictureId != null){
            oldPicture = this.getById(pictureId);
            ThrowUtils.throwIf(oldPicture == null,ErrorCode.NOT_FOUND_ERROR,"图片不存在");
            //只有本人和管理员可更新图片
            if(!oldPicture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
            //校验空间是否一致
            //如果没传spaceId，则复用之前图片的spaceId,
            if(spaceId == null && oldPicture.getSpaceId() != null){
                spaceId = oldPicture.getSpaceId();
            }
            //如果传了spaceId，则校验是否一致
            if(spaceId != null){
                ThrowUtils.throwIf(ObjUtil.notEqual(spaceId,oldPicture.getSpaceId()),ErrorCode.PARAMS_ERROR,"空间id不一致");
            }
        } else {
            oldPicture = null;
        }
        //2.上传图片，得到信息
        //按照用户id划分目录 => 按照空间进行划分
        String uploadPathPrefix;
        if(spaceId == null){
            uploadPathPrefix = String.format("public/%s", loginUser.getId());
        }else{
            uploadPathPrefix = String.format("space/%s", spaceId);
        }
        //根据inputSource 的类型区分上传方式
        PictureUploadTemplate pictureUploadTemplate = filePictureUpload;
        if(inputSource instanceof String){
            pictureUploadTemplate = urlPictureUpload;
        }
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSource, uploadPathPrefix);
        //3.修改数据库
        //造要入库的图片信息
        Picture picture = new Picture();
        BeanUtils.copyProperties(uploadPictureResult,picture);
        //补充空间id
        picture.setSpaceId(spaceId);
        //两个图片名称不一样，单独引入
        String picName = uploadPictureResult.getPicName();
        //支持从外层传递传递图片名称
        if(pictureUploadRequest != null && StrUtil.isNotBlank(pictureUploadRequest.getPicName())){
            picName = pictureUploadRequest.getPicName();
        }
        picture.setName(picName);
        //补充用户id
        picture.setUserId(loginUser.getId());

        if(pictureId != null){
            //如果是更新，需要补充id和编辑时间
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }
        //补充待审核参数
        this.fillReviewParams(picture,loginUser);

        //开启事务
        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            if(finalSpaceId != null) {
                //更新空间额度大小
                //计算空间大小变化量和图片数量变化量
                long sizeDelta = picture.getPicSize() - (oldPicture == null ? 0 : oldPicture.getPicSize());
                //等于空，总数+1，不等于空，删1加1 不变
                long countDelta = (oldPicture == null ? 1 : 0);
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId)
                        .setSql("total_size = total_size + " + sizeDelta)
                        .setSql(countDelta == 1,"total_count = total_count + 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            //如果是更新，需把此前图片从存储桶删除
            if(oldPicture != null){
                //删除cos库webp格式原图和缩略图
                this.clearPictureFile(this.getById(oldPicture.getId()));
            }
            //操作数据库
            boolean result = this.saveOrUpdate(picture);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败");
            //不需要返回值呀
            return true;
        });
        return PictureVO.objToVo(picture);
    }

    /**
     * 删除图片
     * @param pictureId
     * @param loginUser
     */
    @Override
    public void deletePicture(long pictureId, User loginUser){
        ThrowUtils.throwIf(pictureId <= 0,ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null,ErrorCode.NO_AUTH_ERROR);
        // 判断是否存在
        Picture oldPicture = this.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        this.checkPictureAuth(loginUser,oldPicture);
        // 操作数据库
        //添加事务
        transactionTemplate.execute(status ->{
            if(oldPicture.getSpaceId() != null) {
                //更新空间额度
                spaceService.lambdaUpdate()
                        .eq(Space::getId, oldPicture.getSpaceId())
                        .setSql("total_size = total_size - " + oldPicture.getPicSize())
                        .setSql("total_count = total_count -1")
                        .update();
            }
            //删除cos库webp格式原图和缩略图
            this.clearPictureFile(oldPicture);
            //删除照片
            boolean result = this.removeById(pictureId);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
            return true;
        });

    }

    /**
     * 编辑图片
     * @param pictureEditRequest
     * @param loginUser
     * @return
     */
    @Override
    public boolean editPicture(PictureEditRequest pictureEditRequest, User loginUser){
        ThrowUtils.throwIf(pictureEditRequest == null,ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null,ErrorCode.NO_AUTH_ERROR);

        // 将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureEditRequest, picture);
        // 将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        // 设置编辑时间
        picture.setEditTime(new Date());
        // 数据校验
        validPicture(picture);
        // 判断是否存在
        long id = pictureEditRequest.getId();
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验权限
        checkPictureAuth(loginUser, oldPicture);
        //补充待审核参数
        fillReviewParams(picture,loginUser);
        // 操作数据库
        return this.updateById(picture);
    }

    /**
     * 通过id查询图片
     * @param id
     * @param loginUser
     * @return
     */
    @Override
    public Picture getPictureById(long id, User loginUser){
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Picture picture = this.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        //管理员也不能查看私有图库
        //图片空间权限校验:只有本人可以看到私有空间的图片
        if(picture.getSpaceId() != null) {
            this.checkPictureAuth(loginUser, picture);
        }
        return picture;
    }

    /**
     * 根据Picture的字段获取查询条件
     * @param pictureQueryRequest 可获取查询条件的用户字段
     * @return 查询条件queryWrapper
     */
    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {

        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if(pictureQueryRequest == null){
            return queryWrapper;
        }

        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        //搜索词（同时搜名称、简介等）
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        Long spaceId = pictureQueryRequest.getSpaceId();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();

        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();

        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long reviewerId = pictureQueryRequest.getReviewerId();



        if(StrUtil.isNotBlank(searchText)){
            //同时搜名称、简介,拼接查询条件
            //and (name like "%xxx%" or introduction like "%xxx%")
            queryWrapper.and(qw -> qw.like("name",searchText)
                    .or()
                    .like("introduction",searchText)
            );
        }
        //JSON数组查询 所有标签都存在
        if(CollUtil.isNotEmpty(tags)){
            // and (tag like "%\"java\"%" and like "%\"python\"%")
            for(String tag : tags){
                queryWrapper.like("tags", "\" " + tag + "\"");
            }
        }
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "user_id", userId);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "space_id", spaceId);
        queryWrapper.isNull(nullSpaceId,"space_id");
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "pic_format", picFormat);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "pic_width", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "pic_height", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "pic_size", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "pic_scale", picScale);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "review_status", reviewStatus);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "review_message", reviewMessage);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewer_id", reviewerId);




        // 排序

        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }


    /**
     * 获取单个图片封装，关联用户信息
     * @param picture
     * @return
     */
    @Override
    public PictureVO getPictureVO(Picture picture) {

       //对象封装类
        PictureVO pictureVO = PictureVO.objToVo(picture);
        //关联查询用户信息
        Long userId = picture.getUserId();
        if(userId != null && userId >= 0){
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }

    /**
     * 分页获取图片封装
     * @param picturePage
     * @return
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage) {
        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }
        // 对象列表 => 封装对象列表
        List<PictureVO> pictureVOList = pictureList.stream().
                map(PictureVO::objToVo).
                collect(Collectors.toList());
        // 1. 关联查询用户信息，获取去重后的userId
        Set<Long> userIdSet = pictureList.stream()
                .map(Picture::getUserId).
                collect(Collectors.toSet());
        // 根据id 查询多条用户列表，在根据id 进行分组
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            pictureVO.setUser(userService.getUserVO(user));
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }

    @Override
    public Page<Picture> listPictureByPage(PictureQueryRequest pictureQueryRequest, User loginUser) {

        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        //空间权限校验
        if(pictureQueryRequest.getSpaceId() == null){
            //查询公共图库
            //普通用户默认只能看到审核通过的数据
            pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            pictureQueryRequest.setNullSpaceId(true);
        }else{
            //查询私有空间
            Space space = spaceService.getById(pictureQueryRequest.getSpaceId());
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR,"空间不存在");
            if(!space.getUserId().equals(loginUser.getId())){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"没有权限");
            }
        }
        // 查询数据库
        return this.page(new Page<>(current, size),
                this.getQueryWrapper(pictureQueryRequest));
    }


    /**
     * 校验图片
     * @param picture
     */
    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }

    /**
     * 审核图片
     * @param pictureReviewRequest
     * @param loginUser
     */
    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
        //1.校验参数
        ThrowUtils.throwIf(pictureReviewRequest == null,ErrorCode.PARAMS_ERROR);
        Long id = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        PictureReviewStatusEnum reviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        String reviewMessage = pictureReviewRequest.getReviewMessage();
        if(id == null || reviewStatusEnum == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //2.判断图片是否存在
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        //3.校验审核状态是否重复
        if(oldPicture.getReviewStatus().equals(reviewStatus)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请勿重复审核");
        }
        //4.操作数据库
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureReviewRequest,picture);
        picture.setReviewerId(loginUser.getId());
        picture.setReviewTime(new Date());
        boolean result = this.updateById(picture);
        ThrowUtils.throwIf(!result,ErrorCode.SYSTEM_ERROR,"审核失败");
    }

    /**
     * 填充审核参数
     * @param picture
     * @param loginUser
     */
    @Override
    public void fillReviewParams(Picture picture, User loginUser){
        //判断是否为管理员，是自动过审，不是添加待过审状态
        if(userService.isAdmin(loginUser)){
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewerId(loginUser.getId());
            picture.setReviewTime(new Date());
            picture.setReviewMessage("管理员自动过审");
        }else{
            //非管理员，无论是编辑还是创建默认都是待审核
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }
    }

    /**
     * 批量上传图片
     * @param pictureUploadByBatchRequest
     * @param loginUser
     * @return 成功创建的图片数
     */
    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        //1.校验参数
        String searchText = pictureUploadByBatchRequest.getSearchText();
        Integer count = pictureUploadByBatchRequest.getCount();
        ThrowUtils.throwIf(StrUtil.isBlank(searchText), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(count > 30, ErrorCode.PARAMS_ERROR, "最多 30 条");
        //名称前缀默认为搜素关键词
        String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
        if(namePrefix == null){
            namePrefix = searchText;
        }
        // 要抓取的地址
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("获取页面失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取页面失败");
        }
        Element div = document.getElementsByClass("dgControl").first();
        if (ObjUtil.isNull(div)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取元素失败");
        }
        Elements imgElementList = div.select("img.mimg");
        int uploadCount = 0;
        for (Element imgElement : imgElementList) {
            String fileUrl = imgElement.attr("src");
            if (StrUtil.isBlank(fileUrl)) {
                log.info("当前链接为空，已跳过: {}", fileUrl);
                continue;
            }
            // 处理图片上传地址，防止出现转义问题
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }
            // 上传图片
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            if(StrUtil.isNotBlank(namePrefix)){
                //设置图片名称，序号连续递增
                pictureUploadRequest.setPicName(namePrefix + (uploadCount + 1) );
            }
            try {
                PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
                log.info("图片上传成功, id = {}", pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.error("图片上传失败", e);
                continue;
            }
            if (uploadCount >= count) {
                break;
            }
        }
        return uploadCount;
    }

    /**
     * 清除图片文件
     * @param oldPicture
     */
    @Async //异步执行
    @Override
    public void clearPictureFile(Picture oldPicture) {
   /*     //如果图片关联多条记录，则不删除
        Long count = this.lambdaQuery()
                .eq(Picture::getUrl, pictureUrl).count();
        if(count > 1){
            return;
        }*/
        /**
         * url:  https://yuntuku-1339641919.cos.ap-beijing.myqcloud.com
         *             //public/1883712518426566658/2025-02-05_5tjhmof2.
         *
         * uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + compressedCiObject.getKey());
         */
        String pictureUrl = oldPicture.getUrl();
        String host = String.format(cosClientConfig.getHost() +"/");
        //如果包含域名，则去掉
        if(pictureUrl.contains(host)){
            pictureUrl = pictureUrl.replace(host, "");
        }
        //删除图片
        cosManager.deleteObject(pictureUrl);
        //删除缩略图
        String thumbnailUrl = oldPicture.getThumbnailUrl();
        if(StrUtil.isNotBlank(thumbnailUrl)){
            //如果包含域名，则去掉
            if(thumbnailUrl.contains(host)){
                thumbnailUrl = thumbnailUrl.replace(host, "");
                cosManager.deleteObject(thumbnailUrl);
            }
        }
    }

    /**
     * 校验图片空间的权限
     * @param loginUser
     * @param picture
     */
    @Override
    public void checkPictureAuth(User loginUser, Picture picture) {
        //本人可以看到和修改私有空间的图片
        if(picture.getSpaceId() != null){
            if (ObjUtil.notEqual(picture.getUserId(),loginUser.getId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }else{
            //管理员和本人可以修改公共图库里的图片
            if(!userService.isAdmin(loginUser) && ObjUtil.notEqual(picture.getUserId(),loginUser.getId())){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
    }


}




